<template>
  <div>
    <el-dialog
      v-model="createVisible"
      :title="operation == 'create' ? '添加配置分类' : '编辑配置分类'"
      @before-ok="createOk"
      @close="close(createRef)"
      width="500px"
      top="100px"
    >
      <el-form
        :model="createForm"
        ref="createRef"
        :rules="createRules"
        label-width="130px"
        size="default"
        v-loading="initLoading"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="父级分类：" prop="pid">
              <el-select v-model="createForm.pid" class="form-select-fil">
                <el-option
                  v-for="item in parentTree"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类名称：" prop="title">
              <el-input v-model="createForm.title" placeholder="请输入分类名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类字段标识：" prop="eng_field">
              <el-input v-model="createForm.eng_field" placeholder="请输入分类字段标识"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述：" prop="desc">
              <el-input v-model="createForm.desc" placeholder="请输入描述"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="'图标：'" prop="icon">
              <el-input
                v-model="createForm.icon"
                :prefix-icon="
                  () => {
                    return h('span', { class: ['icon', createForm.icon] });
                  }
                "
              >
                <template #append>
                  <el-button
                    @click="
                      () => {
                        selectModalIconRef.open();
                      }
                    "
                  >
                    图标
                  </el-button>
                  <select-icon-modal
                    ref="selectModalIconRef"
                    @change="iconChange"
                  ></select-icon-modal>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="类型：" prop="type">
              <el-radio-group v-model="createForm.type">
                <el-radio :label="1" border>默认</el-radio>
                <el-radio :label="2" border>列表</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态：" prop="status">
              <el-radio-group v-model="createForm.status">
                <el-radio :label="0">关闭</el-radio>
                <el-radio :label="1">开启</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序：" prop="sort">
              <el-input-number
                v-model="createForm.sort"
                :min="0"
                :max="10000"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="flex center">
          <el-button @click="createVisible = false">取消</el-button>
          <el-button type="primary" @click="createOk(createRef)" :loading="btnLoading" :disabled="btnLoading"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
export default {
  name:'systemConfigTabCreate'
}
</script>
<script lang="ts" setup >
import { ref, h, reactive, getCurrentInstance, nextTick } from "vue";
import type { FormInstance } from "element-plus";
import type { Result , ResultError } from "@/types";

import {
  getConfigTabSelectTree,
  createConfigTab,
  getConfigTabDetail,
  updateConfigTab,
} from "@/api/system/config";

const {
  proxy: { $message, $utils },
} = getCurrentInstance() as any;

const operation = ref<string>("create");

const operationId = ref<number>(0);

const createVisible = ref<boolean>(false);

const createRef = ref<typeof FormInstance>();

const createForm = ref({
  title: "",
  eng_field: "",
  pid: null,
  icon: "",
  sort: 0,
  status: 1,
  type: 1,
  desc:''
});

const initLoading = ref<boolean>(true)

const toInit = () => {
  initCascader();
  if (!operationId.value) {
    initLoading.value = false
    return;
  }
  getConfigTabDetail({id:operationId.value})
    .then((res: Result) => {
      createForm.value.title = res.data.title;
      createForm.value.eng_field = res.data.eng_field;
      createForm.value.pid = res.data.pid;
      createForm.value.icon = res.data.icon;
      createForm.value.sort = res.data.sort;
      createForm.value.status = res.data.status.value;
      createForm.value.type = res.data.type;
      createForm.value.desc = res.data.desc;
      initLoading.value = false
    })
    .catch((err:ResultError) => {
      $utils.errorMsg(err);
    });
};

const createRules: any = reactive({
  title: [{ required: true, message: "分类名称不能为空！" }],
  eng_field: [{ required: true, message: "分类英文标识不能为空！" }],
});

const emit = defineEmits(["success"]);

const btnLoading = ref<boolean>(false)


const createOk = async (formEl:typeof FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid:any, fields: any) => {
    if (valid) {
      if(btnLoading.value){
        return
      }
      btnLoading.value = true
      let operationApi: any = null;
      if (operation.value == "create") {
        operationApi = createConfigTab(createForm.value);
      } else {
        operationApi = updateConfigTab(Object.assign({
          id:operationId.value
        },createForm.value));
      }
      operationApi
        .then((res: Result) => {
          $message.success(res.message);
          close(formEl);
          emit("success");
          btnLoading.value = false
        })
        .catch((err: ResultError) => {
          $utils.errorMsg(err);
          btnLoading.value = false
        });
    }
  });
};

const parentTree = ref<any>([]);

const initCascader = () => {
  let obj: any = {};
  if (operationId.value) {
    obj["pid"] = operationId.value;
  }
  getConfigTabSelectTree(obj)
    .then((res: Result) => {
      parentTree.value = res.data;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const selectModalIconRef = ref<any>();

const iconChange = (icon: string) => {
  createForm.value.icon = icon;
};

const open = (id:number = 0) => {
  initLoading.value = true
  if (id != 0) {
    operation.value = "update";
    operationId.value = id;
  } else {
    operation.value = "create";
  }
  nextTick(() => {
    toInit();
  });
  createVisible.value = true;
};

const close = async (formEl: typeof FormInstance | undefined) => {
  if (formEl) {
    formEl.resetFields();
  }
  operationId.value = 0;
  createVisible.value = false;
};

defineExpose({ open });
</script>
    <style scoped>
</style>